package com.blockmeta.bbs.immodule.widget;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;

import com.blockmeta.bbs.baselibrary.base.adapter.BaseAdapter;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.utils.DimentionsUtil;
import com.blockmeta.bbs.immodule.bean.beaninterface.IFriendsEntry;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * @author AirThor
 * @date 2019/3/5.
 * IM 联系人列表装饰器 在每组的第一个item上方绘制Letter 其它的绘制分割线
 */
public class FriendsLetterItemDecoration extends RecyclerView.ItemDecoration {
    private static final int mLetterHeight = DimentionsUtil.dp2px(BaseApp.getApp(),36f);
    private static final int DP_68 = DimentionsUtil.dp2px(BaseApp.getApp(),68f);
    private static final int DP_100 = DimentionsUtil.dp2px(BaseApp.getApp(),100f);
    private static final int DP_14 = DimentionsUtil.dp2px(BaseApp.getApp(),14f);
    private static final int DP_1 = DimentionsUtil.dp2px(BaseApp.getApp(),1f);

    private List<IFriendsEntry> mFriendsEntries;

    private int[] mSectionIndices;

    private String[] mLetters;

    private SparseArray<String> mSparseIntArray = new SparseArray<>();

    private FriendsLetterItemDecoration(){}

    private Paint mDividerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Paint mLetterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    private int mDividerMargin = DP_68;

    private BaseAdapter<IFriendsEntry, BaseViewHolder> mBaseAdapter;
    /**
     * 是否以首字母分组
     */
    private boolean groupByLetter = true;

    public void setGroupByLetter(boolean groupByLetter) {
        this.groupByLetter = groupByLetter;
    }

    /**
     * 处于编辑模式时 分割线要更短
     * @param editMode 是否编辑模式
     */
    public void setEditable(boolean editMode) {
        mDividerMargin = editMode?DP_100:DP_68;
    }

    public FriendsLetterItemDecoration(BaseAdapter<IFriendsEntry, BaseViewHolder> adapter) {
        mBaseAdapter = adapter;
        adapter.registerAdapterDataObserver(new DataObserver());
        mFriendsEntries = adapter.getData();

        mDividerPaint.setColor(Color.parseColor("#F8F8F8"));
        mDividerPaint.setStrokeWidth(DP_1);

        mLetterPaint.setColor(Color.BLACK);
        mLetterPaint.setTextSize(DP_14);
        mLetterPaint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));

        mSectionIndices = getSectionIndices();
        mLetters = getSectionLetters();
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildLayoutPosition(view);
        int headerCount = mBaseAdapter.getHeaderLayoutCount();
        int dataPosition = position-headerCount;
        boolean isHeaderView = mBaseAdapter.getItemViewType(position)== BaseQuickAdapter.HEADER_VIEW;
        if (!isHeaderView&&firstInSection(dataPosition)){
            outRect.top = mLetterHeight;
        }else if (!isHeaderView){
            outRect.top = DP_1;
        }
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (!(layoutManager instanceof LinearLayoutManager)){return;}
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            int position = parent.getChildLayoutPosition(child);
            int dataPosition = position-mBaseAdapter.getHeaderLayoutCount();
            boolean isHeaderView = mBaseAdapter.getItemViewType(position)== BaseQuickAdapter.HEADER_VIEW;
            if (!isHeaderView&&firstInSection(dataPosition)){
                drawLetter(c,child,dataPosition);
            }else if (!isHeaderView){
                drawLine(c,child);
            }
        }
    }

    private void drawLine(Canvas c, View child) {
        float left = 0;
        float y = child.getTop()-DP_1/2f;
        float right = child.getRight();
        c.drawLine(left,y,right,y,mDividerPaint);
    }

    private void drawLetter(Canvas c, View child,int position) {
        float left = child.getLeft();
        float top = child.getTop()-mLetterHeight;
        float right = child.getRight();
        float bottom =child.getTop();
        c.drawRect(left,top,right,bottom,mDividerPaint);
        float y =(bottom-top-mLetterPaint.getFontMetrics().descent+mLetterPaint.getFontMetrics().ascent)/2-mLetterPaint.getFontMetrics().ascent;
        c.drawText(mFriendsEntries.get(position).getLetter(),DP_14,top+y,mLetterPaint);
    }

    /**
     * 获取每个部分的第一个的位置存在一个数组里
     * @return 每个部分的index
     */
    private int[] getSectionIndices() {
        if (!groupByLetter) {return null;}
        ArrayList<Integer> sectionIndices = new ArrayList<>();
        if (mFriendsEntries.size() > 0) {
            char lastFirstChar = mFriendsEntries.get(0).getLetter().charAt(0);
            sectionIndices.add(0);
            for (int i = 1; i < mFriendsEntries.size(); i++) {
                if (mFriendsEntries.get(i).getLetter().charAt(0) != lastFirstChar) {
                    lastFirstChar = mFriendsEntries.get(i).getLetter().charAt(0);
                    sectionIndices.add(i);
                }
            }
            int[] sections = new int[sectionIndices.size()];
            for (int i = 0; i < sectionIndices.size(); i++) {
                sections[i] = sectionIndices.get(i);
            }
            return sections;
        }
        return null;
    }

    /**
     * @return 获取每个部分的首字母
     */
    private String[] getSectionLetters() {
        if (null != mSectionIndices) {
            String[] letters = new String[mSectionIndices.length];
            for (int i = 0; i < mSectionIndices.length; i++) {
                letters[i] = mFriendsEntries.get(mSectionIndices[i]).getLetter();
            }
            return letters;
        }
        return null;
    }

    /**
     * 根据给出的首字母 返回该字母分组的第一个元素索引
     * @param letter 首字母
     * @return 索引
     */
    public int getLetterPosition(String letter){
        for (int i = 0;mLetters!=null&&i < mLetters.length; i++) {
            if (mLetters[i].equals(letter)){
                return mSectionIndices[i];
            }
        }
        return -1;
    }
    /**
     * 判断当前的position是不是每个组的第一个
     */
    private boolean firstInSection(int position){
        if (mSectionIndices==null||!groupByLetter) {return false;}
        for (int i = 0; i < mSectionIndices.length; i++) {
            if (mSectionIndices[i] == position){
                return true;
            }
        }
        return false;
    }


    class DataObserver extends RecyclerView.AdapterDataObserver{
        public DataObserver() {

        }

        @Override
        public void onChanged() {
            updateData();
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            updateData();
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
            updateData();
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            updateData();
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            updateData();
        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
            updateData();
        }
    }

    private void updateData(){
        mFriendsEntries = mBaseAdapter.getData();
        mSectionIndices = getSectionIndices();
        mLetters = getSectionLetters();
    }
}
